<template>
  <div class="select-box" ref="a">
    <van-popup v-model="show" position="bottom" class="birthday-popup">
      <div class="birthday-title flex jcb">
        <div class="span">{{title}}</div>
        <div class="sure" @click="change">{{sureBtn}}</div>
      </div>
      <van-picker ref="defaultPicker" v-if="type === 'default'"
                  :columns="columns"
                  :value-key="valueKey"
                  :default-index="dfValue"
                  @confirm="onConfirm"
                  @change="onChange"></van-picker>
      <van-datetime-picker v-model="value"
                           v-else
                           ref="datePicker"
                           :type="type"
                           :min-date="minDate"
                           :max-date="maxDate"
                           :formatter="formatter"/>
    </van-popup>
  </div>
</template>

<script>
  export default {
    name: "GlSelect",
    props: {
      type: {
        type: String,
        default: 'default',
      },
      title: {
        type: String,
        default: '请选择',
      },
      dfValue: {
        default: 0
      },
      minDate: {
        type: Date,
      },
      maxDate: {
        type: Date,
      },
      valueKey: {
        type: String,
        default: 'text',
      },
      sureBtn: {
        type: String,
        default: '完成',
      },
      columns: {
        type: Array,
        default() {
          return [];
        },
      },
      formatter: {
        type: Array,
        default(type, value) {
          return value;
        },
      },
    },
    data() {
      return {
        show: true,
        picker: null,
        value: '',
      }
    },
    watch: {
      dfValue(val) {
        this.value = val;
      },
      type(val) {
        this.picker = this.$refs[val === 'default' ? 'defaultPicker' : 'datePicker'];
      },
      show(val) {
        if (!val) {
          let popup = this.$refs.a;
          setTimeout(() => popup.parentElement.removeChild(popup), 1000);
        }
      },
    },
    created() {
    },
    mounted() {
      this.picker = this.$refs[this.type === 'default' ? 'defaultPicker' : 'datePicker'];
    },
    methods: {
      change() {
        this.$emit('sure', this.type === 'default' ? this.picker.getValues() : this.value);
        this.show = false;
      },
      onChange(val) {
        // console.log(val);
        this.$emit('change', this.picker.getValues());
      },
      onConfirm(val) {
        // console.log(val);
      },
    },
  }
</script>

<style scoped lang="less">
  .birthday-popup {
    /deep/ .van-picker__toolbar {
      height: 0;
      overflow: hidden;
    }
    .birthday-title {
      padding: 0 .78rem;
      color: #333;
      font-size: 1rem;
      line-height: 2.69rem;
      border-bottom: .06rem solid #eee;
      .sure {
        font-size: .88rem;
        color: #208fff;
      }
    }
  }
</style>
